/* -*- Mode:Prolog; coding:ISO-8859-1; -*- */
:- ensure_loaded([list_utils, heuristics, score_tools,user_score]). 


:- multifile saved_solution/3.
:- dynamic  saved_solution/3.


best_solution(BestSolutionHere, OutTest, ScoreBest) :-
        log('Current best solution:'),
        findall(Score-Info-Solution, saved_solution(Solution, Info, Score), ThisRound),
        sort(ThisRound, [ScoreBest-_InfoBest-BestSolutionHere | _]),
        portray_list(BestSolutionHere),
        print('with score '), log(ScoreBest),
        get_examples(Examples),
        theory_test_with_asserted_bg(BestSolutionHere, Examples, OutTest).







combine_solutions(Return) :-
        log('Combining solutions, all solutions:'),
        findall(Score-Info-Solution, saved_solution(Solution, Info, Score), ThisRound),
        portray_list(ThisRound),
        sort(ThisRound, [ScoreBest-_InfoBest-BestSolutionHere | _]),
        print('Selected best, current solution: \n'), portray_list(BestSolutionHere),
        print('with score '), log(ScoreBest),
        combine_solutions(BestSolutionHere, ScoreBest, Return).
                        
        
combine_solutions(Current, CurrentScore, Return) :-
        findall(ThisScore-Info-EvaluateThisSol, 
                (saved_solution(Solution, Info, _Score),
                 union(Solution, Current, EvaluateThisSol),
                 evaluate(EvaluateThisSol,  ThisEval),
                 heuristic_score(EvaluateThisSol, ThisEval, Info,  ThisScore),
                 save_solution(EvaluateThisSol, Info, ThisScore)
                ),         
                ThisRound),
       sort(ThisRound, [ScoreBest-_InfoBest-_BestSolutionHere | _Tail]),
%        log('New round'),
%        portray_list([ScoreBest-InfoBest-BestSolutionHere | Tail]),
        (ScoreBest < CurrentScore
                ->
                print('Selected best, current solution: \n'), portray_list(NewSolution),
                print('with score '), log(NewScore),
                combine_solutions(NewSolution, NewScore, Return)
                ;
                log('No improvement, terminating '),
                Return=Current
        ).
        